package com.dynamic.mybatis.autoconfigure;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.dynamic.mybatis.core.metadata.DynamicConfiguration;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({DynamicMybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class DynamicMybatisAutoConfig {



    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean
    public static SqlSessionFactory sqlSessionFactory(DataSource dataSource, DynamicMybatisProperties properties) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        //数据源
        factoryBean.setDataSource(dataSource);
        //mybatis配置
        factoryBean.setTypeAliasesPackage(properties.getTypeAliasesPackage());
        factoryBean.setMapperLocations(properties.resolveMapperLocations());
        //mybatis Configuration 配置
        DynamicConfiguration configuration = properties.getConfiguration();
        configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
        factoryBean.setConfiguration(configuration);
        return factoryBean.getObject();
    }
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @ConditionalOnMissingBean
    public DynamicSqlSessionTemplate dynamicSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        return new DynamicSqlSessionTemplate(sqlSessionTemplate);
    }
}